#!/bin/sh -e

### BEGIN INIT INFO
# Provides:          webapp
# Required-Start:    $local_fs $network $syslog
# Required-Stop:     $local_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts webapp
# Description:       starts webapp skeleton using start-stop-daemon
### END INIT INFO

NAME=webapp
DAEMON=webapp-cherryd
VIRTUALENV=/var/www/webapp
USER=www-data
GROUP=www-data

EXEC=$VIRTUALENV/bin/$DAEMON
PIDFILE=/var/run/$NAME/$DAEMON.pid
ARGS="-i serve -e production -P $VIRTUALENV/backend/$NAME \
  -d -p $PIDFILE -u $USER -g $GROUP"


. /lib/lsb/init-functions

[ -x "$EXEC" ] || exit 0


start() {
  log_begin_msg "Starting $NAME..."
  test -e /var/run/$NAME || install -m 755 -o $USER -g $GROUP -d /var/run/$NAME
  if start-stop-daemon --start --pidfile $PIDFILE --startas $EXEC -- $ARGS; then
    log_end_msg 0
  else
    log_end_msg $?
  fi
}

stop() {
  log_begin_msg "Stopping $NAME..."
  if start-stop-daemon --stop --retry TERM/10/KILL/5 --pidfile $PIDFILE; then
    log_end_msg 0
  else
    if start-stop-daemon --stop --retry TERM/10/KILL/5 --name $DAEMON; then
      log_end_msg 0
    else
      log_end_msg $?
    fi
  fi
}

status() {
  status_of_proc $EXEC $NAME -p $PIDFILE && exit 0 || exit $?
}


case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  status)
    status
    ;;
  *)
    echo "Usage: $NAME {start|stop|restart|reload|status}" >&2
    exit 1
    ;;
esac

exit 0